#include <unistd.h>
#include <stdio.h>


template<typename T>
int loopDataGather(int (*callback)(T arg, char * buf, int len),
                   Sensor sensor, char * buf, int len, char delim, T arg)
{
    int ret = 0;

    if (sensor < 0)  
        return -1;

    while (ret == 0)
    {
        bool discard = false;
        int i = 0;

        do
        {
            if (i >= len)
            {
                discard = true;
                i = 0;
            }

            int amt = read(sensor, buf+i, 1);

            if (amt < 0)
                return -1;

            i += amt;
        }
        while (buf[i-1] != delim);

        if (!discard && i > 1)
            ret = callback(arg, buf, i);
    }

    return ret;
}
